import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { http } from '@/utils/request'
import { ElMessage } from 'element-plus'

export const useAccountConfigStore = defineStore('accountConfig', () => {
  // 状态
  const configs = ref([])
  const currentConfig = ref(null)
  const loading = ref(false)
  const pagination = ref({
    page: 1,
    size: 10,
    total: 0
  })

  // 计算属性
  const hasConfigs = computed(() => configs.value.length > 0)
  const activeConfig = computed(() => configs.value.find(config => config.isActive === 1))

  // 获取账号配置列表
  const fetchAccountConfigs = async (accountId, params = {}) => {
    loading.value = true
    try {
      const { page = 1, size = 10, status } = params
      const queryParams = { page, size }
      if (status !== undefined) queryParams.status = status

      const response = await http.get(`/accounts/${accountId}/configs`, queryParams)
      const { list, total } = response.data

      configs.value = list
      pagination.value.total = total
      pagination.value.page = page
      pagination.value.size = size

      return response
    } catch (error) {
      configs.value = []
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取账号配置详情
  const getAccountConfig = async (accountId, configId) => {
    try {
      const response = await http.get(`/accounts/${accountId}/configs/${configId}`)
      currentConfig.value = response.data
      return response.data
    } catch (error) {
      throw error
    }
  }

  // 创建账号配置
  const createAccountConfig = async (accountId, configData) => {
    try {
      const response = await http.post(`/accounts/${accountId}/configs`, configData)
      ElMessage.success('账号配置创建成功')

      // 刷新列表
      await fetchAccountConfigs(accountId)

      return response.data
    } catch (error) {
      throw error
    }
  }

  // 更新账号配置
  const updateAccountConfig = async (accountId, configId, configData) => {
    try {
      const response = await http.put(`/accounts/${accountId}/configs/${configId}`, configData)
      ElMessage.success('账号配置更新成功')

      // 刷新列表
      await fetchAccountConfigs(accountId)

      return response.data
    } catch (error) {
      throw error
    }
  }

  // 激活账号配置
  const activateAccountConfig = async (accountId, configId) => {
    try {
      const response = await http.post(`/accounts/${accountId}/configs/${configId}/activate`)
      ElMessage.success('账号配置已激活')

      // 刷新列表
      await fetchAccountConfigs(accountId)

      return response
    } catch (error) {
      throw error
    }
  }

  // 删除账号配置
  const deleteAccountConfig = async (accountId, configId) => {
    try {
      const response = await http.delete(`/accounts/${accountId}/configs/${configId}`)
      ElMessage.success('账号配置已删除')

      // 刷新列表
      await fetchAccountConfigs(accountId)

      return response
    } catch (error) {
      throw error
    }
  }

  // 获取账号有效配置（合并全局配置）
  const getEffectiveConfig = async (accountId) => {
    try {
      const response = await http.get(`/accounts/${accountId}/effective-config`)
      return response.data
    } catch (error) {
      throw error
    }
  }

  // 从全局配置创建账号配置
  const createFromGlobalConfig = async (accountId, globalConfigId, createData) => {
    try {
      const response = await http.post(
        `/accounts/${accountId}/configs/from-global/${globalConfigId}`,
        createData
      )
      ElMessage.success('基于全局配置创建成功')

      // 刷新列表
      await fetchAccountConfigs(accountId)

      return response.data
    } catch (error) {
      throw error
    }
  }

  // 获取账号配置历史记录
  const getAccountConfigHistory = async (accountId, configId, params = {}) => {
    try {
      const { page = 1, size = 10 } = params
      const response = await http.get(
        `/accounts/${accountId}/configs/${configId}/history`,
        { page, size }
      )
      return response.data
    } catch (error) {
      throw error
    }
  }

  // 清空状态
  const clearConfigs = () => {
    configs.value = []
    currentConfig.value = null
    pagination.value = {
      page: 1,
      size: 10,
      total: 0
    }
  }

  return {
    // 状态
    configs,
    currentConfig,
    loading,
    pagination,

    // 计算属性
    hasConfigs,
    activeConfig,

    // 方法
    fetchAccountConfigs,
    getAccountConfig,
    createAccountConfig,
    updateAccountConfig,
    activateAccountConfig,
    deleteAccountConfig,
    getEffectiveConfig,
    createFromGlobalConfig,
    getAccountConfigHistory,
    clearConfigs
  }
})